<template>
  <div class="pie-chart">
    <div class="total">
      <h1>总数</h1>
      <p>{{total}}</p>
    </div>
    <div ref="pie" class="pie-container"></div>
  </div>
</template>

<script>
export default {
  name: 'pie-chart',
  props: {
    data: {
      type: Array,
      default: () => {
        return []
      }
    },
    title: {
      type: String
    }
  },
  data() {
    return {
      total: 0
    }
  },
  watch: {
    data: {
      handler() {
        this.setChart()
      }
    }
  },
  methods: {
    setChart() {
      if (this.data) {
        this.initChart()
      }
    },
    initChart() {
      const legendConfig = {
        orient: 'horizontal',
        icon: 'roundRect',
        textStyle: {
          color: '#000000'
        },
        itemWidth: 8,
        itemHeight: 8,
        itemGap: 12,
        formatter: this.getPercent
      }
      const options = {
        title: {
          text: this.title
        },
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} ({d}%)'
        },
        legend: [
          {
            left: '10%',
            bottom: 14,
            data: this.data.map(item => item.name),
            ...legendConfig
          }
        ],
        series: [
          {
            name: '访问来源',
            type: 'pie',
            roseType: 'area',
            center: ['50%', '35%'],
            radius: ['38%', '53%'],
            itemStyle: {
              borderRadius: 8
            },
            avoidLabelOverlap: false,
            color: ['#FF4F5C', '#3FFFC3', '#FFCC0C', '#128CFF', '#7F58FF', '#FFB8B4', '#5D7092', '#FD9E5F', '#5D7092', '#607DFF'],
            data: this.data
          }
        ]
      }
      this.$echarts.dispose(this.$refs.pie)
      const chart = this.$echarts.init(this.$refs.pie)
      window.onresize = chart.resize
      chart.setOption(options)
    },
    getPercent(name) {
      const sum = this.data
      let total = 0
      let tarValue
      for (let i = 0, l = sum.length; i < l; i++) {
        total += sum[i].value
        if (sum[i].name === name) {
          tarValue = sum[i].value
        }
      }
      let p = parseInt(((tarValue / total) * 100))
      this.total = total
      if (p < 10) {
        p = '0' + p
      }
      if (isNaN(p)) {
        p = 0
      }
      return name + ' ' + ' ' + p
    }
  }
}
</script>

<style lang="scss" scoped>
  .pie-chart {
    position: relative;
    height: 350px;

    .total {
      top: 100px;
      position: absolute;
      text-align: center;
      width: 100%;
      z-index: 100;

      > h1 {
        font-size: 22px;
        font-weight: 500;
        color: #000000;
        line-height: 22px;
      }

      > p {
        font-size: 20px;
        font-weight: 600;
        color: #000000;
        line-height: 20px;
      }
    }

    .pie-container {
      height: 100%
    }
  }

</style>
